package com.marktotop.service.impl;

import com.marktotop.exception.GlobalException;
import com.marktotop.pojo.User;
import com.marktotop.mapper.UserMapper;
import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import com.marktotop.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.utils.CookieUtil;
import com.marktotop.utils.MD5Util;
import com.marktotop.utils.UUIDUtil;
import com.marktotop.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MarkToTop
 * @since 2021-06-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 登录
     *
     * @param loginVO
     * @param request
     * @param response
     * @return
     */
    @Override
    public ResultBean login(LoginVO loginVO, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        // 参数校验通过 Validation注解实现
        // 根据手机号获取用户
        User user = userMapper.selectById(mobile);
        if (null == user){
            throw  new GlobalException(ResultCode.LOGIN_USER_NOT_FOUND);
        }
        // 判断第二次MD5加密的密码和数据库中的密码是否相同
        if (!MD5Util.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            throw  new GlobalException(ResultCode.LOGIN_PASSWORD_ERROR);
        }
        //生成cookie
        String ticket = UUIDUtil.uuid();
        //将用户信息存入redis中
        redisTemplate.opsForValue().set("user:" + ticket, user);
        // request.getSession().setAttribute(ticket,user);
        CookieUtil.setCookie(request, response, "userTicket", ticket);
        return ResultBean.ok();
    }


    /**
     * 从Cookie获取用户
     *
     * @param userTicket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getUserFromCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(userTicket)){
            return null;
        }
        User user = (User)redisTemplate.opsForValue().get("user:" +userTicket);
        if (user != null){
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }
}
